package com.lh_travel.lohas.activity.user;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.activity.HotelDetailActivity;
import com.lh_travel.lohas.adapter.BaseRecyclerAdapter;
import com.lh_travel.lohas.adapter.BaseRecyclerHolder;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.CommentIntentBean;
import com.lh_travel.lohas.domain.HotelListBean;
import com.lh_travel.lohas.domain.UserBean;
import com.lh_travel.lohas.domain.respon;
import com.lh_travel.lohas.utils.DateTimeUtil;
import com.lh_travel.lohas.utils.MapUtil;
import com.lh_travel.lohas.utils.Preferences;
import com.lh_travel.lohas.utils.ScrPtHelper;
import com.lh_travel.lohas.widget.DefineLoadMoreView;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxListCallback;
import com.tamic.novate.callback.RxResultCallback;
import com.tamic.novate.callback.RxStringCallback;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CollectionActivity extends baseActivity {

    private Toolbar toolbar;
    private ImageButton img_back;
    private RadioButton rb_all;
    private RadioButton rb_1m;
    private RadioButton rb_nm;
    private UserBean userBean;
    private List<HotelListBean.SimpleHotelBean> collectList = new ArrayList<>();
    private SwipeMenuRecyclerView srv;
    private int position;
    private BaseRecyclerAdapter<HotelListBean.SimpleHotelBean> collectAdapter;
    private String lat, lng;
    private String time;
    private int page = 1;
    public int actionType;
    public final int finish = 0;
    public final int INIT = 1;
    public final int LOADMORE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_collection);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        img_back = (ImageButton) findViewById(R.id.img_back);

        rb_all = (RadioButton) findViewById(R.id.rb_all);
        rb_1m = (RadioButton) findViewById(R.id.rb_1m);
        rb_nm = (RadioButton) findViewById(R.id.rb_nm);

        srv = (SwipeMenuRecyclerView) findViewById(R.id.srv);

    }

    @Override
    public void bindListner() {
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    actionType = INIT;
                    page = 1;
                    time = "0";
                    showViewLoad();
                    new api(mContext).getCollect(userBean.token, "1", time, lat, lng, page, collectBean);

                }

            }
        });

        rb_1m.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    actionType = INIT;
                    time = "1";
                    page = 1;
                    showViewLoad();
                    new api(mContext).getCollect(userBean.token, "1", time, lat, lng, page, collectBean);

                }

            }
        });

        rb_nm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    actionType = INIT;
                    time = "2";
                    page = 1;
                    showViewLoad();
                    new api(mContext).getCollect(userBean.token, "1", time, lat, lng, page, collectBean);

                }

            }
        });
    }

    @Override
    public void ensureUI() {
        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);

        userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);

        lat = mApp.getPreference(Preferences.LOCAL.LAT);
        lng = mApp.getPreference(Preferences.LOCAL.LNG);

        if (lat == null) {
            lat = "";
            lng = "";

        } else if (mApp.getPreference(Preferences.LOCAL.COUNTRY).equals("cn")) {

            //转换成百度地图
            // lat = MapUtil.gcj02_To_Bd09()

            Double latDouble = Double.valueOf(mApp.getPreference(Preferences.LOCAL.LAT));
            Double lngDouble = Double.valueOf(mApp.getPreference(Preferences.LOCAL.LNG));

            lat = MapUtil.gcj02_To_Bd09(latDouble, lngDouble)[0] + "";
            lng = MapUtil.gcj02_To_Bd09(latDouble, lngDouble)[1] + "";

        } else {

            lat = mApp.getPreference(Preferences.LOCAL.LAT);
            lng = mApp.getPreference(Preferences.LOCAL.LNG);

        }

        rb_all.setChecked(true);
    }

    private void initXrv() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        srv.setLayoutManager(layoutManager);

        collectAdapter = new BaseRecyclerAdapter<HotelListBean.SimpleHotelBean>(mContext, collectList, R.layout.item_collect) {
            @Override
            public void convert(BaseRecyclerHolder holder, final HotelListBean.SimpleHotelBean item, int position, boolean isScrolling) {

                holder.setImageByUrl(R.id.img_pic, item.picture, R.drawable.default_bg200x200);

                holder.setText(R.id.tv_discount, "优惠了" + item.rate + "%");

                double distent = new BigDecimal(item.distance).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                holder.setText(R.id.tv_distent, distent + "km");

                holder.setText(R.id.tv_name, item.title);

                LinearLayout container = holder.getView(R.id.ll_star_container);

                switch (item.star) {
                    case "豪华":

                        setStar(5, container);

                        break;

                    case "高档":

                        setStar(4, container);

                        break;

                    case "舒适":

                        setStar(3, container);

                        break;

                    case "经济":

                        setStar(2, container);

                        break;
                }

                //地标
                holder.setText(R.id.tv_position, "距离" + item.position_name + item.pos_distance + "km");

                //评分
                holder.setText(R.id.tv_comment, item.fake_comment + item.fake_comment_score + "/" + item.fake_comment_num + "评论");

                //价格
                holder.setText(R.id.tv_discount_price, "¥" + item.min_price);

                //原价
                holder.setText(R.id.tv_ori_price, "¥" + item.max_price);
                holder.setTextFlag(R.id.tv_ori_price, 1);

                //优惠
                double value = new BigDecimal(item.rate).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                if (value > 0.1) {
                    holder.setText(R.id.tv_discount, "优惠" + ((int) (value * 100)) + "%");
                    holder.setViewsVisable(R.id.tv_discount, true);

                } else {
                    holder.setViewsVisable(R.id.tv_discount, false);
                }

                final TextView name = holder.getView(R.id.tv_name);

                holder.setViewClickLisenter(R.id.ll_main, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, HotelDetailActivity.class);

                        CommentIntentBean bean = new CommentIntentBean();

                        bean.belong = item.belong;
                        bean.id = item.id;
                        bean.checkIn = DateTimeUtil.formatDateTime(DateTimeUtil.gainCurrentDate(), "yyyy-MM-dd");
                        bean.checkOut = DateTimeUtil.formatDateTime(DateTimeUtil.addDateTime(DateTimeUtil.gainCurrentDate(), 24), "yyyy-MM-dd");
                        bean.keyWord = item.title;
                        intent.putExtra("detail", bean);
                        intent.putExtra("star", item.star);

                        mContext.startActivity(intent, ActivityOptions.makeSceneTransitionAnimation((Activity) mContext,
                                /*new Pair<View, String>(img, "TRANSITIONIMAGE"),*/ new Pair<View, String>(name, "TRANSITIONTITLE")).toBundle());
                    }
                });
            }
        };

        srv.setSwipeMenuCreator(new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {

                SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);

                int height = ViewGroup.LayoutParams.MATCH_PARENT;
                int width = (int) ScrPtHelper.pt2px(mContext, 140);

                deleteItem.setText("删除");
                deleteItem.setTextSize(16);
                deleteItem.setTextColor(Color.WHITE);
                deleteItem.setBackgroundColor(Color.RED);

                deleteItem.setHeight(height);
                deleteItem.setWidth(width);

                swipeRightMenu.addMenuItem(deleteItem);
            }
        });

        srv.setSwipeMenuItemClickListener(new SwipeMenuItemClickListener() {

            private String collect_id;

            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                menuBridge.closeMenu();
                position = menuBridge.getAdapterPosition();

                collect_id = collectList.get(position).id;

                showMyDialog("提示", "确认取消收藏?", "确定", "取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        new api(mContext).collectDel(userBean.token, collect_id, delCallBack);
                    }
                });

            }
        });

        SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {

                page++;
                actionType = LOADMORE;

                new api(mContext).getCollect(userBean.token, "1", time, lat, lng, page, collectBean);

            }
        };

        DefineLoadMoreView loadMoreView = new DefineLoadMoreView(this);
        srv.addFooterView(loadMoreView); // 添加为Footer。
        srv.setLoadMoreView(loadMoreView); // 设置LoadMoreView更新监听。
        srv.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。

        srv.setAdapter(collectAdapter);

    }

    private void setStar(int count, LinearLayout container) {

        container.removeAllViews();

        for (int i = 0; i < count; i++) {

            View view = View.inflate(mContext, R.layout.item_stars, null);

            container.addView(view);

        }
    }

    private RxResultCallback<HotelListBean> collectBean = new RxResultCallback<HotelListBean>() {
        @Override
        public void onNext(Object tag, int code, String message, HotelListBean response) {

            dismissViewLoad();

            if (code == 200) {

                switch (actionType) {
                    case INIT:

                        collectList.clear();
                        collectList.addAll(response.collect_list);

                        if (collectAdapter != null) {

                            collectAdapter.notifyDataSetChanged();
                        } else {
                            initXrv();
                        }

                        break;

                    case LOADMORE:
                        collectList.addAll(response.collect_list);
                        collectAdapter.notifyDataSetChanged();

                        break;
                }

                if (collectList.size() < response.total_count) {
                    srv.loadMoreFinish(false, true);

                } else {
                    srv.loadMoreFinish(false, false);

                }
            } else if (code == 101 || code == 401) {

                collectList.clear();
                collectAdapter.notifyDataSetChanged();
                srv.loadMoreFinish(true, false);

            }
        }

        @Override
        public void onError(Object tag, Throwable e) {
            dismissViewLoad();
        }

        @Override
        public void onCancel(Object tag, Throwable e) {
            dismissViewLoad();
        }
    };

    private RxStringCallback delCallBack = new RxStringCallback() {
        @Override
        public void onNext(Object tag, String response) {
            respon result = new Gson().fromJson(response, new TypeToken<respon>() {
            }.getType());

            if (result.code.equals("200")) {

                collectList.remove(position);

                collectAdapter.notifyDataSetChanged();

            }

            showMessage(result.message);
        }

        @Override
        public void onError(Object tag, Throwable e) {

        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }
    };
}
